package udp

import (
	"gitee.com/injoyai/goutil/net/conn"
	"gitee.com/injoyai/goutil/string/logs/v1"
	"log"
	"net"
	"sync"
	"time"
)

// Server 只管发,不确定是否发送成功
// 定义一个协议,总包,一定需要响应,不然就是不在线,然后分包序号进行校验补发
type Server struct {
	port    int
	connMap map[string]*conn.Conn
	connMu  sync.RWMutex //锁
}

// NewServer 最大发送124字节
func NewServer(port int) *Server {
	return &Server{
		port:    port,
		connMap: make(map[string]*conn.Conn),
		connMu:  sync.RWMutex{},
	}
}

func (this *Server) Run() error {
	listen, err := net.ListenUDP("udp", &net.UDPAddr{
		IP:   nil,
		Port: this.port,
		Zone: "",
	})
	if err != nil {
		return err
	}
	defer listen.Close()
	co := 0
	go func() {
		for {
			time.Sleep(time.Second * 3)
			logs.Debug(co)
		}
	}()
	for {
		buff := make([]byte, 124)
		n, addr, err := listen.ReadFromUDP(buff)
		if err != nil {
			return err
		}
		bytes := buff[:n]
		log.Println(addr, string(bytes))
		listen.WriteToUDP(bytes, addr)
		co++
	}

}
